/*
 * Copyright (C) 2018 The Asiainfo-Ability Authors
 *
 *      Licensed under the Apache License, Version 2.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *          http://www.apache.org/licenses/LICENSE-2.0
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

package org.asiainfo.ability.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.asiainfo.ability.base.code.SystemCode;
import org.asiainfo.ability.base.service.TraceService;
import org.asiainfo.ability.base.utils.ExceptionUtils;
import org.asiainfo.ability.base.utils.Response;
import org.asiainfo.ability.base.code.Constants;
import org.asiainfo.ability.gateway.context.AbilityRequestContext;
import org.asiainfo.ability.gateway.custom.CustomHttpServletRequest;
import org.asiainfo.ability.gateway.service.AbilityGatewayFacade;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.RouteLocator;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.web.util.UrlPathHelper;

import java.io.UnsupportedEncodingException;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER;

/**
 * @Author: visen
 * @Date: 2018/1/21
 * @Description:
 */
public class AbilityCheckFilter extends ZuulFilter {
    private static final Logger logger = LogManager.getLogger(AbilityCheckFilter.class);

    private AbilityGatewayFacade gatewayFacade;
    private RouteLocator routeLocator;
    private UrlPathHelper urlPathHelper;
    @Autowired
    private TraceService traceService;

    public AbilityCheckFilter(final AbilityGatewayFacade gatewayFacade, final RouteLocator routeLocator,
                              final UrlPathHelper urlPathHelper) {
        this.gatewayFacade = gatewayFacade;
        this.routeLocator = routeLocator;
        this.urlPathHelper = urlPathHelper;
    }


    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FORM_BODY_WRAPPER_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    private void setResponseBody(RequestContext ctx, String body) {
        ctx.setSendZuulResponse(false);
        ctx.setResponseStatusCode(Constants.ERRORHTTPSCODE);
        ctx.set("isSuccess", false);
        try {
            ctx.setResponseBody(new String(body.getBytes("GBK"), "ISO-8859-1"));
        } catch (UnsupportedEncodingException e) {
            ExceptionUtils.logTrace(logger, e);
        }
    }


    @Override
    public Object run() {
        //FormBodyWrapperFilter
        RequestContext ctx = RequestContext.getCurrentContext();
        try {

            String uri = ctx.getRequest().getRequestURI();
            if (uri.startsWith(gatewayFacade.getBaseUrl())) {
                ctx.setRequest(new CustomHttpServletRequest(ctx.getRequest()));
                AbilityRequestContext requestContext = AbilityRequestContext.createContext(ctx.getRequest()
                        , ctx.getResponse());
                ctx.set(AbilityRequestContext.CONTEXT_KEY, requestContext);
                String error = gatewayFacade.check(requestContext);
                if (error != null) {
                    setResponseBody(ctx, error);
                } else {
                    traceService.saveCallerTrace(requestContext.getCallerTrace());
                }
            } else {
                setResponseBody(ctx, Response.error(SystemCode.invalid_baseurl));
            }
        } catch (Exception e) {
            ExceptionUtils.logTrace(logger, e);
            setResponseBody(ctx, Response.error(SystemCode.unknown));
        }

        return null;
    }


    //local test
    public static void main(String[] args) {
    }

}
